package com.hmall.trade.listener;


import com.hmall.api.pay.PayClient;
import com.hmall.api.pay.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    private final PayClient payClient;



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Order orderDto){
        Long orderId = orderDto.getId();
        //查询订单
        Order order = orderService.getById(orderId);
        if(order == null || order.getStatus()!=1){
            //无效的订单或订单已支付
            return;
        }
        //查询支付单
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        if(payOrderDTO == null){
            return;
        }
        //判断是否支付
        if(payOrderDTO.getStatus() == 3){
            //已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            //未支付，取消订单，回滚库存
            orderService.cancelOrder(orderId);
        }
    }

}
